/*
 *    Copyright 2022 CManLH
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.lifeonwalden.ms.async.runner.thread;

import com.lifeonwalden.ms.async.runner.bean.AsyncRunnerItem;
import com.lifeonwalden.ms.async.runner.service.RunnerService;
import com.lifeonwalden.ms.common.logger.LoggerUtil;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class Runner implements Runnable {
    private final static Logger logger = LoggerUtil.getLogger(Runner.class);

    private ConcurrentHashMap<Integer, RunnerService> runner;

    private BlockingQueue<AsyncRunnerItem> queue;

    private AtomicInteger runnerCounter;

    public Runner(ConcurrentHashMap<Integer, RunnerService> runner, BlockingQueue<AsyncRunnerItem> queue, AtomicInteger runnerCounter) {
        this.runner = runner;
        this.queue = queue;
        this.runnerCounter = runnerCounter;
    }

    @Override
    public void run() {
        while (true) {
            try {
                AsyncRunnerItem item = queue.take();
                if (Dispatcher.EMPTY == item) {
                    if (runnerCounter.decrementAndGet() >= 1) {
                        logger.info("Runner going to retire.");

                        queue.put(Dispatcher.EMPTY);

                        break;
                    } else {
                        runnerCounter.incrementAndGet();
                    }
                } else {
                    try {
                        RunnerService runnerService = runner.get(item.getRunnerId());
                        if (null != runnerService) {
                            runnerService.run(item.getParameter());
                        } else {
                            logger.error("Not found runner service for id : {}", item.getRunnerId());
                        }
                    } catch (Throwable e) {
                        logger.error("Error happened", e);
                    }
                }
            } catch (InterruptedException e) {
                logger.error("Runner interrupted", e);
            }
        }
    }
}
